﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using SCS.Core.Models.ModelsFontend;
using SCSService;
using SCSInternetBanking.LibertyReserve;

namespace SCS.Core.Controllers
{
    public class ShoppingCartController : BaseFontendController
    {
        //
        // GET: /ShoppingCart/

        public ActionResult Cart()
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        public ActionResult Carts()
        {
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Set up our ViewModel
            var viewModel = new ShoppingCartViewModels
            {
                CartItems = cart.GetListCartItemByCartID(),
                CartTotal = cart.GetTotalValueCartItem(languageId),
                CartCount=cart.GetCountCartItem()
            };

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/Carts", viewModel);
        }


        public ActionResult AddToCart(int id)
        {
            HttpCookie cookie = HttpContext.Request.Cookies["invoice"];

            if (cookie != null)
            {
                return RedirectToAction("PaymentOrder", "Checkout");
            }
            else
            {
                // get Product
                var product = ProductModel.GetProductByID(id);

                // Add it to the shopping cart
                var cart = ShoppingCart.GetCart(this.HttpContext);

                cart.AddToCart(product);

                // Go back to the main store page for more shopping
                return RedirectToAction("Cart");
            }
            
        }

        public ActionResult EmptyCart2()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var list = cart.GetListCartItemByCartID();
            ShoppingCart shopcart = new ShoppingCart();
            foreach (var item in list)
            {
                shopcart.DeleteCartItem(item);
            }
            //shopcart.EmptyCart(cart);

            return Json("1");
        }

        public ActionResult EmptyCart()
        {
            ShoppingCart shopcart = new ShoppingCart();
            shopcart.EmptyCart();

            return Json("1");
        }

        public ActionResult AddMultiToCart(string id)
        {
            int? languageId = null;
            // Add it to the shopping cart
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var arr = id.Split(',');
            // get Product
            var product = ProductModel.GetProductByID(int.Parse(arr[0]));

            if (arr[1] != null && arr[1] != string.Empty)
            {
                int no = int.Parse(arr[1]);
                if (no > 0)
                {
                    for (int i = 0; i < no; i++)
                    {
                        cart.AddToCart(product);
                    }

                }
            }

            double CartTotal = cart.GetTotalValueCartItem(languageId);
            int CartCount = cart.GetCountCartItem();

            long totalCountCard = 0; 
            long number = 0;
            var list = cart.GetListCartItemByCartID();
            foreach(var ite in list)
            {
                number = ite.Count.Value;
                totalCountCard += number;
            }


            var results = totalCountCard + "|" + CartTotal + "|" + CartCount;

            return Json(results);
        }

        public ActionResult AddToCartAjaxTransfer(string id)
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);
            //remove
            cart.EmptyCart();
            //add new
            var product = ProductModel.GetProductByID(int.Parse(id));
            cart.AddToCart(product);
            var result = "1";
            // Go back to the main store page for more shopping
            return Json(result);
        }

        [HttpPost]
        public ActionResult UpdateToCart(string id)
        {
            var arr = id.Split(',');
            // get Product
            var product = ProductModel.GetProductByID(int.Parse(arr[0]));

            // Add it to the shopping cart
            var cart = ShoppingCart.GetCart(this.HttpContext);


            var cartItem = ShoppingCart.GetCartbyRecordID(int.Parse(arr[2]));
            // Get product
            if (cartItem != null)
            {
                //var productDelete = ProductModel.GetProductByID((int)cartItem.ProductID);

                // Remove from cart. Note that for simplicity, we're 
                // removing all rather than decrementing the count.
                for (int i = 0; i < cartItem.Count; i++)
                {
                    cart.RemoveFromCart(int.Parse(arr[2]));
                }

            }


            if (int.Parse(arr[1]) > 1)
            {
                for (int i = 0; i < int.Parse(arr[1]); i++)
                {
                    cart.AddToCart(product);
                }
            }
            else
                cart.AddToCart(product);


            // Go back to the main store page for more shopping
            string result = "" + int.Parse(arr[1]);
            return Json(result);
        }


       


        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            int? languageId = null;
            // Remove the item from the cart
            var cart = ShoppingCart.GetCart(this.HttpContext);

            var cartItem = ShoppingCart.GetCartbyRecordID(id);
            // Get product
            var product = ProductModel.GetProductByID((int)cartItem.ProductID);

            // Remove from cart. Note that for simplicity, we're 
            // removing all rather than decrementing the count.
            for (int i = 0; i < cartItem.Count; i++)
            {
                cart.RemoveFromCart(id);
            }
                
            // Display the confirmation message
            //var results = new ShoppingCartRemoveViewModels
            //{
            //    Message = Server.HtmlEncode(product.ProductName) +
            //        " đã được xóa khỏi giỏ hàng của bạn.",
            //    CartTotal = cart.GetTotalValueCartItem(languageId),
            //    CartCount = cart.GetCountCartItem(),
            //    DeleteId = id
            //};
             double CartTotal = cart.GetTotalValueCartItem(languageId);
             int CartCount = cart.GetCountCartItem();

            var results = id +"|" + CartTotal + "|" + CartCount ;

            return Json(results);
        }


        public JsonResult CheckAccountBalanceLiberty()
        {
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            ShoppingCart cart = new ShoppingCart();
            List<Config_Payment_Method_Website> listMethod = new List<Config_Payment_Method_Website>();
            listMethod = cart.GetListPaymentMethod(siteGuid);

            var liberty = listMethod.Where(p => p.MethodID == 1).FirstOrDefault();

            SCSInternetBanking.LibertyReserve.ApiCredentials g_credentials = new SCSInternetBanking.LibertyReserve.ApiCredentials()
            {
                AccountNumber = liberty.AccountNumber,
                ApiName = liberty.ApiName,
                SecurityWord = liberty.SecurityWord
            };

            SCSInternetBanking.LibertyReserve.IApiAgent agent = SCSInternetBanking.LibertyReserve.ApiAgentFactory.Create(SCSInternetBanking.LibertyReserve.ApiProtocol.Xml, g_credentials);
            agent.RequireValidSslCertificate = true;
            string re = "-1";
            try
            {
                Balance balance = agent.Balance();
                re = String.Format("{0:n}", 1, balance.Usd) ?? "-1";
            }
            catch (Exception)
            {
                re = "-1";
            }

            return Json(re);
        }
    }
}
